import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    userId: localStorage.getItem('userId') ? parseInt(localStorage.getItem('userId') || '0') : null, // 从 localStorage 恢复 userId
    userToken: localStorage.getItem('userToken') || null,
    username: localStorage.getItem('username') || null, // 新增用户名
  }),
  getters: {
    isLoggedIn: (state) => !!state.userToken,
    currentUserId: (state) => state.userId,
    currentUsername: (state) => state.username,
  },
  actions: {
    setUserId(id: number) {
      this.userId = id;
      localStorage.setItem('userId', id.toString()); // 将 userId 存入 localStorage
    },
    setUserToken(token: string) {
      this.userToken = token;
      localStorage.setItem('userToken', token);
    },
    setUsername(username: string) {
      this.username = username;
      localStorage.setItem('username', username);
    },
    clearUser() {
      this.userId = null;
      this.userToken = null;
      this.username = null;
      localStorage.removeItem('userId'); // 清除 localStorage 中的 userId
      localStorage.removeItem('userToken');
      localStorage.removeItem('username');
    },
  },
});